import Vue from 'vue'
import Router from 'vue-router'
import store from './store'

import AdminLTE from 'components/AdminLTE.vue'
import url from 'url'

import Index from 'components/Index.vue'
const Screen  = () => import(/* webpackChunkName: 'screen' */ 'components/Screen.vue')
const Channel = () => import(/* webpackChunkName: 'channel' */ 'components/Channel.vue')

const RecordContainer = () => import(/* webpackChunkName: 'record' */ 'components/RecordContainer.vue')
const RecordChannelList = () => import(/* webpackChunkName: 'record' */ 'components/RecordChannelList.vue')
const RecordListBox = () => import(/* webpackChunkName: 'record' */ 'components/RecordListBox.vue')
const RecordTimeBox = () => import(/* webpackChunkName: 'record' */ 'components/RecordTimeBox.vue')

const PlaybackListBox = () => import(/* webpackChunkName: 'device_record' */ 'components/PlaybackListBox.vue')
const PlaybackTimeBox = () => import(/* webpackChunkName: 'device_record' */ 'components/PlaybackTimeBox.vue')

// const Player = () => import(/* webpackChunkName: 'player' */ 'components/Player.vue')
const Config = () => import(/* webpackChunkName: 'config' */ 'components/Config.vue')
const BaseConfig = () => import(/* webpackChunkName: 'config' */ 'components/ConfigBase.vue')
const NVSConfigTab = () => import(/* webpackChunkName: 'config' */ 'components/ConfigNVSTab.vue')
const GBConfigTab = () => import(/* webpackChunkName: 'config' */ 'components/ConfigGBTab.vue')
const ISUPConfigTab = () => import(/* webpackChunkName: 'config' */ 'components/ConfigISUP.vue')
const About = () => import(/* webpackChunkName: 'about' */ 'components/About.vue')

const LiveList = () => import( /* webpackChunkName: 'live' */ 'components/LiveList.vue')
const RecordPlanConf = () => import( /* webpackChunkName: 'planconf' */ 'components/RecordPlanConf.vue')
const LogList = () => import(/* webpackChunkName: 'log' */ 'components/LogList.vue')
const UserList = () => import(/* webpackChunckName: 'user' */ 'components/UserList.vue')
const Dashboard = () => import( /* webpackChunkName: 'dashboard' */ 'components/Dashboard.vue')

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: '/',
      component: AdminLTE,
      children: [
        {
          path: '',
          component: Dashboard,
          props: true
        }, {
          path: 'index/:mode',
          component: Index,
          props: true
        }, {
          path: 'screen',
          component: Screen,
          props: true
        }, {
          path: 'channel',
          redirect: '/channel/1'
        }, {
          path: 'channel/:page',
          component: Channel,
          meta: { needLogin: true },
          props: true
        }, {
          path: 'live/:page',
          component: LiveList,
          meta: { needLogin: true },
          props: true
        }, {
          path: 'plan',
          component: RecordPlanConf,
          meta: { needLogin: true },
          props: true
        }, {
          path: 'record',
          component: RecordContainer,
          children: [{
            path: '',
            redirect: 'channels/1'
          }, {
            path: 'channels/:page',
            component: RecordChannelList,
            props: true
          }, {
            path: 'listview/:id/:day?',
            component: RecordListBox,
            props: true
          }, {
            path: 'timeview/:id/:day?',
            component: RecordTimeBox,
            props: true
          }]
        }, {
          path: 'playback',
          component: RecordContainer,
          children: [{
            path: '',
            redirect: 'channels/1'
          }, {
            path: 'channels/:page',
            component: RecordChannelList,
            props: true
          }, {
            path: 'listview/:id/:day?',
            component: PlaybackListBox,
            props: true
          }, {
            path: 'timeview/:id/:day?',
            component: PlaybackTimeBox,
            props: true
          }]
        }, {
          path: 'user',
          meta: { needLogin: true },
          redirect: '/user/1'
        }, {
          path: 'user/:page',
          meta: { needLogin: true },
          component: UserList,
          props: true
        }, {
          path: 'logs',
          meta: { needLogin: true },
          redirect: '/logs/1'
        }, {
          path : 'logs/:page',
          meta: { needLogin: true },
          component: LogList,
          props: true
        }, {
          path: 'config',
          meta: { needLogin: true },
          component: Config,
          children: [{
            path: '',
            redirect: 'base'
          }, {
            path: 'base',
            component: BaseConfig,
            props: true
          }, {
            path: 'nvss',
            component: NVSConfigTab,
            props: true
          }, {
            path: 'gbs',
            component: GBConfigTab,
            props: true
          }, {
            path: 'isup',
            component: ISUPConfigTab,
            props: true
          }]
        }, {
          path: 'about',
          meta: { needLogin: true },
          component: About
        }, {
          path: 'logout',
          async beforeEnter(to, from, next) {
            await store.dispatch("logout");
            window.location.href = `/login`;
          }
        }, {
          path: '*',
          redirect: '/'
        }
      ]
    }
  ],
  linkActiveClass: 'active'
})

router.beforeEach(async (to, from, next) => {
  var serverInfo = await store.dispatch("getServerInfo");
  if(serverInfo) {
    document.title = serverInfo.LogoText || "LiveNVR";
  }
  var userInfo = await store.dispatch("getUserInfo");
  // if (serverInfo && serverInfo.APIAuth === false && !userInfo) {
  //   next();
  //   return;
  // }
  var menuMap = store.state.menus.reduce((pval, cval) => {
    pval[cval.path] = cval;
    return pval;
  }, {})
  var pageRoles = []; // 前往页面要求角色列表
  var menu = menuMap[to.path];
  if (menu) {
    pageRoles.push(...(menu.roles || []));
  }
  if (!userInfo) {
    // if ((serverInfo && serverInfo.APIAuth && serverInfo.LiveStreamAuth) || to.matched.some(record => (record.meta.needLogin || record.meta.roles))) {
    if ((serverInfo && serverInfo.APIAuth) || to.matched.some(record => (record.meta.needLogin || record.meta.roles))) {
      if (to.fullPath == '/') {
        window.location.href = `/login`;
      } else {
        var _url = url.parse(window.location.href, true);
        _url.hash = to.fullPath;
        window.location.href = `/login?r=${encodeURIComponent(url.format(_url))}`;
      }
      return;
    }
    // if (serverInfo && serverInfo.APIAuth && !serverInfo.LiveStreamAuth && serverInfo.AnonymousAccess && to.path == '/') {
    //   next("/index/icons");
    //   return;
    // }
    next();
    return;
  }
  if (!pageRoles.length) {
    next();
    return;
  }
  if (!pageRoles.some(pr => (userInfo.roles.some(ur => (ur == pr || ur == '超级管理员'))))) { // 两个角色列表没有交集
    console.log("page", to.path, "require roles", pageRoles.join(','));
    console.log("user", userInfo.name, "has roles", userInfo.roles.join(','));
    for(var menu of store.state.menus) { // 取首个有交集的菜单
      if(menu.path) {
        if(!menu.roles || menu.roles.some(pr => (userInfo.roles.some(ur => (ur == pr))))) {
          next(menu.path);
          return;
        }
      }
    }
    // next('/devices')
    // window.location.href = `/#/devices/1`;
    return;
  }
  next();
})

export default router;